import 'dart:async';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import '../../common/extentsion/localStorageExample.dart';
import './ViewModel/loginViewModel.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class Login extends StatefulWidget {
  static const String routeName = "login";

  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      // appBar: buildAppBar(),
      body: LoginContext(),
    );
  }
}

class LoginContext extends StatefulWidget {
  const LoginContext({Key? key}) : super(key: key);

  @override
  State<LoginContext> createState() => _LoginContextState();
}

class _LoginContextState extends State<LoginContext> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  late VideoPlayerController _videoController;
  int countdown = 0;
  Timer? _timer;

  static const double borderRadius = 25.0;
  static const double buttonHeight = 45.0;
  static const double buttonWidthFactor = 0.45;
  static const EdgeInsets textFieldMargin =
      EdgeInsets.only(left: 35, right: 35, top: 50);
  static const EdgeInsets textFieldPadding =
      EdgeInsets.only(right: 20, left: 20);
  static const EdgeInsets rowPadding = EdgeInsets.only(right: 35, left: 35);
  static const EdgeInsets containerPadding =
      EdgeInsets.only(left: 35, right: 35);

  @override
  void initState() {
    super.initState();
    _videoController =
        VideoPlayerController.asset('assets/video/video_test2.mp4')
          ..initialize().then((_) {
            setState(() {});
            _videoController.play();
          })
          ..setLooping(true);
  }

  @override
  void dispose() {
    _videoController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  @override
  //发送验证码
  sendCode() async {
    final params = {"tel": _phoneController.text};
    final response = await Api().sendCode(params);
    if (response) {
      countdown = 60;
      startCountdown();
    }
  }
  //登录
  login() async {
    final params = {"tel": _phoneController.text,"code":_codeController.text};
    final response = await Api().login(params);
    if (response){
      Future.delayed(const Duration(seconds: 2),(){
        Navigator.pop(context);
      });

    }
  }

  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final screenWidth = MediaQuery.of(context).size.width;
    final videoWidth = screenHeight * _videoController.value.aspectRatio;
    return Stack(
      children: [
        if (_videoController.value.isInitialized)
          Positioned(
            top: 0,
            left: (screenWidth - videoWidth) / 2,
            child: SizedBox(
              height: screenHeight,
              child: AspectRatio(
                aspectRatio: _videoController.value.aspectRatio,
                child: VideoPlayer(_videoController),
              ),
            ),
          )
        else
          const Center(child: CircularProgressIndicator()),
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: buildLoginForm(),
        ),
      ],
    );
  }

  Widget buildLoginForm() {
    return Column(
      children: [
        // buildContainerBackBtn(),
        const SizedBox(height: 150),
        buildTitle(),
        buildSubtitle(),
        buildPhoneTextField(),
        const SizedBox(height: 30),
        buildCodeRow(),
        const SizedBox(height: 50),
        buildLoginButton(),
      ],
    );
  }

  Container buildContainerBackBtn() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: const EdgeInsets.only(left: 20, top: 80),
      child: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: const Icon(Icons.arrow_back_ios_new_outlined,
              color: Colors.white)),
    );
  }

  Widget buildTitle() {
    return const Text(
      "手机号登录",
      style: TextStyle(
        color: Colors.white,
        fontSize: 30,
        fontWeight: FontWeight.bold,
      ),
    );
  }

  Widget buildSubtitle() {
    return const Text(
      "未登录手机号登录成功后将自动注册",
      style: TextStyle(color: Colors.white, fontSize: 15),
    );
  }

  Widget buildPhoneTextField() {
    return Container(
      margin: textFieldMargin,
      padding: textFieldPadding,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(borderRadius),
      ),
      child: TextField(
        style: const TextStyle(color: Colors.black, fontSize: 15),
        controller: _phoneController,
        keyboardType: TextInputType.number,
        decoration: const InputDecoration(
          hintText: '请输入您的手机号',
          border: InputBorder.none,
        ),
      ),
    );
  }

  Widget buildCodeRow() {
    return Padding(
      padding: rowPadding,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            padding: textFieldPadding,
            width: MediaQuery.of(context).size.width * buttonWidthFactor,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(borderRadius),
            ),
            child: TextField(
              style: const TextStyle(color: Colors.black, fontSize: 15),
              controller: _codeController,
              decoration: const InputDecoration(
                hintText: '验证码',
                border: InputBorder.none,
              ),
            ),
          ),
          buildCodeButton(),
        ],
      ),
    );
  }

  Widget buildCodeButton() {
    return OutlinedButton(
      style: const ButtonStyle(
        foregroundColor: WidgetStatePropertyAll(Colors.white),
        side: WidgetStatePropertyAll(
          BorderSide(
            color: Colors.white,
            width: 1.0,
          ),
        ),
      ),
      onPressed: countdown == 0
          ? () {
              setState(() {
                if (_phoneController.text == '') {
                  EasyLoading.showToast("请输入手机号");
                  return;
                }
                sendCode();
              });
            }
          : null,
      child: Text(countdown == 0 ? '获取验证码' : '重新发送:${countdown}s'),
    );
  }

  Widget buildLoginButton() {
    return Container(
      padding: containerPadding,
      width: double.infinity,
      height: buttonHeight,
      child: ElevatedButton(
        style: const ButtonStyle(
          foregroundColor: WidgetStatePropertyAll(Colors.white),
          backgroundColor: WidgetStatePropertyAll(Colors.orange),
        ),
        onPressed: () async {
          final phone = _phoneController.text;
          final code = _codeController.text;
          try {
            if (phone == '' || code == '') {
              EasyLoading.showToast("请输入手机号及验证码");
              return;
            }
            login();
          } catch (e) {
            print("存储或读取数据时出错: $e");
          }
        },
        child: const Text("登 录"),
      ),
    );
  }

  void startCountdown() {
    const oneSec = Duration(seconds: 1);
    _timer = Timer.periodic(oneSec, (Timer timer) {
      if (countdown == 0) {
        setState(() {
          timer.cancel();
        });
      } else {
        setState(() {
          countdown--;
        });
      }
    });
  }
}
